<?php

namespace app\admin\controller;

use think\Controller;
use app\common\lib\IAuth;

class Login extends Base
{
    public function _initialize()
    {
    }
    public function index()
    {
        //判断是否登陆
        $isLogin = $this->isLogin();
        if ($isLogin) {
            return $this->redirect('index/index');
        } else {
            return $this->fetch();
        }
    }
    public function check()
    {
        if (request()->isPost()) {
            $data = input('post.');
            if (!captcha_check($data['code'])) {
                //验证失败
                $this->error('验证码错误');
            }
            try {
                $user = model('AdminUser')->get(['username' => $data['username']]);
                if (!$user || $user->status != config('code.status_normal')) {
                    $this->error('用户名不存在');
                } else {
                    if ($user['password'] == IAuth::setPassword($data['password'])) {
                        $udata = [
                            'last_login_ip'   => request()->ip(),
                            'last_login_time' => time(),
                        ];
                        model('AdminUser')->save($udata, ['id' => $user->id]);
                    } else {
                        $this->error('密码不正确！');
                    }
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            session(config('session.session_user'), $user, config('session.session_user_scopt'));
            $this->success('登陆成功', 'index/index');
        } else {
            $this->error('请求不合法!');
        }
    }

    /***
     * 清除session
     * 跳转到登陆页面
     */
    public function logout()
    {
        session(null, config('session.session_user_scopt'));
        $this->redirect('login/index');
    }
}
